import redis
import socket
from datetime import datetime

log_info_file = open('/proc/1/fd/1', 'w')
log_error_file = open('/proc/1/fd/2', 'w')
def check_ip_port(ip,port):
    try:
        # 尝试连接到 Redis 主节点
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(2)
        result = sock.connect_ex((ip, port))
        sock.close()
        return result == 0
    except Exception as e:
        print(f"{datetime.now()}==检查 Redis {ip}状态出错: {e}", file=log_error_file)
        return False

def to_slave(ip_master,port_master,password_master,ip_slave,port_slave,password_slave):
    """redis设置为从节点"""
    try:
        r = redis.Redis(host=ip_slave, port=port_slave, password=password_slave)
        r.config_set('masterauth', password_master)
        result = r.replicaof(ip_master, port_master)
        if result == b'OK':
            print(f'{datetime.now()}====redis:已成功切换为从节点', file=log_info_file)
        else:
            print(f'{datetime.now()}====redis:切换从节点:异常:{result}', file=log_error_file)
    except Exception as e:
        print(f"{datetime.now()}==to_slave报错: {e}", file=log_error_file)

def to_master(ip_master,port_master,password_master):
    """redis设置为主节点"""
    try:
        r = redis.Redis(host=ip_master, port=port_master, password=password_master)
        result = r.execute_command('REPLICAOF', 'NO', 'ONE')
        if result == b'OK':
            print(f'{datetime.now()}====redis:已成功切换为主节点', file=log_info_file)
        else:
            print(f'{datetime.now()}====redis:切换从节点:异常:{result}', file=log_error_file)
    except Exception as e:
        print(f"{datetime.now()}==to_master报错: {e}", file=log_error_file)